<?php
namespace app\common\controller;
use think\Controller;
use think\Db;
use think\Exception;
use think\Request;
use think\Session;
use app\user\controller\Login;

class Secret extends Controller{
    public $Secret = null;
    public function _initialize(){


        $this->Secret = $this->make_secret();

        while ( $this->Secret == $this->query($this->Secret) ){
            $this->Secret = $this->make_secret();
        }
        Db::name('secret_map')
            ->insert(['secret'=>$this->Secret]);
    }
    public function query($secret){
        $res = Db::name('secret_map')
            ->field('secret')
            ->where('secret ="'.$secret.'"')
            ->find();
        if(!empty($res)){
            return $res['secret'];
        }else{
            return 'Null';
        }
    }

    /**
     * @param int $length
     * @return string
     * 随机密钥
     */
    function make_secret( $length = 4 )
    {
        // 密码字符集，可任意添加你需要的字符
        $chars = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
            'i', 'j', 'k', 'l','m', 'n', 'o', 'p', 'q', 'r', 's',
            't', 'u', 'v', 'w', 'x', 'y','z', 'A', 'B', 'C', 'D',
            'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L','M', 'N', 'O',
            'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y','Z',
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
        // 在 $chars 中随机取 $length 个数组元素键名
        $keys = array_rand($chars, $length);
        $secret = '';
        for($i = 0; $i < $length; $i++)
        {
            // 将 $length 个数组元素连接成字符串
            $secret .= $chars[$keys[$i]];
        }
        return $secret;
    }

}